package com.moyun.modelclass.fragment.model;


import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.moyun.modelclass.activity.LoginVerificationCodeActivity;
import com.moyun.modelclass.adapter.CommentMutiAdapter;
import com.moyun.modelclass.adapter.ParentCommentAdapter;
import com.moyun.modelclass.base.BaseFragment;
import com.moyun.modelclass.comment.bean.CommentEntity;
import com.moyun.modelclass.comment.bean.CommentMoreBean;
import com.moyun.modelclass.comment.bean.FirstLevelBean;
import com.moyun.modelclass.comment.bean.SecondLevelBean;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.AppCommentApi;
import com.moyun.modelclass.http.api.AppCommentChildrenApi;
import com.moyun.modelclass.http.api.CheckCommentsLikesApi;
import com.moyun.modelclass.http.api.CommentMakeApi;
import com.moyun.modelclass.http.api.LikeCommentApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.CreateFileUtils;
import com.moyun.modelclass.utils.GlideEngine;
import com.moyun.modelclass.view.AndroidBugInputBoxAndSoftKeyboard;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


public class ModelCommentFragment extends BaseFragment implements CommentMutiAdapter.OnCommentClick {
    private TextView tvCommentCommentsNumber;
    private SmartRefreshLayout commentCommentsRefresh;
    private RecyclerView recyclerCommentComments;

    private ImageView ivCommentSendImage;
    private EditText etCommentContent;
    private TextView tvCommentSendContent;
    private FrameLayout flCommentPreviewImage;
    private ImageView tvCommentPreviewImage;
    private ImageView tvCommentPreviewImageDelete;
    private CommentMutiAdapter commentMutiAdapter;
    private File headPortraitFile = null;//头像
    private UpdateImageApi.Bean commentImageBean = null;//评论图片

    private List<CommentMakeApi.CommentMakeRequest> commentList = new ArrayList<>();
    private String mLastId = "";
    private String mModelId = "";//模型id
    private String mCommentId = "";//回复评论id
    private List<String> commentIdList = new ArrayList<>();

    private List<FirstLevelBean> datas = new ArrayList<>();
    private List<MultiItemEntity> data = new ArrayList<>();

    public static ModelCommentFragment newInstance(String modelId) {
        Bundle args = new Bundle();
        args.putString("modelId", modelId);
        ModelCommentFragment fragment = new ModelCommentFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_comment;
    }

    @Override
    protected void assignViews(View view) {
        tvCommentCommentsNumber = (TextView) view.findViewById(R.id.tv_comment_comments_number);
        commentCommentsRefresh = (SmartRefreshLayout) view.findViewById(R.id.comment_comments_refresh);
        recyclerCommentComments = (RecyclerView) view.findViewById(R.id.recycler_comment_comments);

        ivCommentSendImage = (ImageView) view.findViewById(R.id.iv_comment_send_image);
        etCommentContent = (EditText) view.findViewById(R.id.et_comment_content);
        tvCommentSendContent = (TextView) view.findViewById(R.id.tv_comment_send_content);
        flCommentPreviewImage = (FrameLayout) view.findViewById(R.id.fl_comment_preview_image);
        tvCommentPreviewImage = (ImageView) view.findViewById(R.id.tv_comment_preview_image);
        tvCommentPreviewImageDelete = (ImageView) view.findViewById(R.id.tv_comment_preview_image_delete);

        recyclerCommentComments.setLayoutManager(new LinearLayoutManager(mContext));
        commentMutiAdapter = new CommentMutiAdapter(data);
        commentMutiAdapter.setOnCommentClick(this);
        recyclerCommentComments.setAdapter(commentMutiAdapter);
        commentCommentsRefresh.setEnableRefresh(false);
    }

    @Override
    protected void registerListeners() {
        AndroidBugInputBoxAndSoftKeyboard.assistActivity(requireActivity(), true, new AndroidBugInputBoxAndSoftKeyboard.OnChangeListener() {
            @Override
            public void showChange(boolean isShow) {
                if (isShow) {
                    if (CommonConfiguration.isLogin(kv)) {
                        etCommentContent.setCursorVisible(true);
                    } else {
//                        ToastUtils.showShort(getContext().getString(R.string.http_token_error));
                        LoginVerificationCodeActivity.start(requireActivity());
                    }
                } else {
                    etCommentContent.setCursorVisible(false);
                }
            }
        });

//        commentCommentsRefresh.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//                mLastId = "";
//                commentIdList.clear();
//                initCommentsLog(true);
//            }
//        });
        commentCommentsRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                initCommentsLog(false);
            }
        });

        ClickUtils.applySingleDebouncing(tvCommentPreviewImageDelete, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Glide.with(requireActivity()).clear(tvCommentPreviewImage);
                commentImageBean = null;
                flCommentPreviewImage.setVisibility(View.GONE);
            }
        });

        ClickUtils.applySingleDebouncing(tvCommentSendContent, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = etCommentContent.getText().toString();
                if (!content.isEmpty()) {
                    commentList.clear();
                    CommentMakeApi.CommentMakeRequest comment = new CommentMakeApi.CommentMakeRequest();
                    comment.setCommentContent(content);
                    if (commentImageBean != null) {
                        List<String> image = new ArrayList<>();
                        image.add(commentImageBean.getUrl());

                        comment.setImages(image);
                    }
                    comment.setObjectId(mModelId);
                    comment.setTargetId(mCommentId);
                    commentList.add(comment);
                    initCommentMakeApi(commentList);
                } else {
                    ToastUtils.showShort("请输入评论内容");
                }
            }
        });


        ClickUtils.applySingleDebouncing(ivCommentSendImage, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonConfiguration.isLogin(kv)) {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(requireActivity());
                    return;
                }
                KeyboardUtils.hideSoftInput(etCommentContent);
                XXPermissions.with(requireActivity()).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                PictureSelector.create(requireActivity())
                                        .openGallery(SelectMimeType.ofImage())
                                        .setImageEngine(GlideEngine.createGlideEngine())
                                        .setMaxSelectNum(1)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(ArrayList<LocalMedia> result) {
                                                for (LocalMedia media : result) {
                                                    Luban.with(requireActivity())
                                                            .load(media.getRealPath())
                                                            .ignoreBy(50)
                                                            .setTargetDir(CreateFileUtils.getSandboxPath(requireActivity()))
                                                            .setCompressListener(new OnCompressListener() {
                                                                                     @Override
                                                                                     public void onStart() {
                                                                                     }

                                                                                     @Override
                                                                                     public void onSuccess(int index, File compressFile) {
                                                                                         headPortraitFile = compressFile;
                                                                                         Glide.with(mContext)
                                                                                                 .asBitmap()
                                                                                                 .centerCrop()
                                                                                                 .load(PictureMimeType.isContent(media.getPath()) && !media.isCut() && !media.isCompressed() ? Uri.parse(media.getPath()) : media.getPath())
                                                                                                 .placeholder(R.drawable.icon_head_portrait)
                                                                                                 .error(R.drawable.icon_head_portrait)
                                                                                                 .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                                                                                 .into(new BitmapImageViewTarget(tvCommentPreviewImage) {
                                                                                                     @Override
                                                                                                     protected void setResource(Bitmap resource) {
                                                                                                         super.setResource(resource);
                                                                                                         tvCommentPreviewImage.setImageBitmap(ImageUtils.toRound(resource));
                                                                                                     }
                                                                                                 });
                                                                                         initUpdateImageApi(true);
                                                                                     }

                                                                                     @Override
                                                                                     public void onError(int index, Throwable e) {
                                                                                         ToastUtils.showShort("选择图片失败");
                                                                                     }
                                                                                 }
                                                            ).launch();
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                ToastUtils.showShort("获取存储权限失败");
                            }
                        });
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
        mModelId = bundle.getString("modelId", "");
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initCommentsLog(true);
    }

    private void initCommentsLog(boolean isRefresh) {
        if (mModelId == null || mModelId.isEmpty()) {
            ToastUtils.showShort("模型id为空");
            return;
        }
        mLastId = isRefresh ? "" : mLastId;
        EasyHttp.post(requireActivity())
                .api(new AppCommentApi().setType(2).setObjectId(mModelId).setPageSize(CommonConfiguration.page).setLastId(mLastId))
                .request(new HttpCallback<HttpData<CommentEntity>>(this) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(HttpData<CommentEntity> result) {
                        commentCommentsRefresh.finishLoadMore();
                        if (result != null && result.getData() != null && result.getData().getComments().size() > 0) {
                            mLastId = result.getData().getComments().get(result.getData().getComments().size() - 1).getId();
                            Log.e("initCommentsLog==>", mLastId.toString());
                            tvCommentCommentsNumber.setText("评论   " + result.getData().getTotalComment());
                            datas = result.getData().getComments();
                            if (isRefresh) {
                                datas = result.getData().getComments();
                                dataSort(true, 0);
                            } else {
                                List<FirstLevelBean> serviceList = new CopyOnWriteArrayList<>(result.getData().getComments());
                                for (FirstLevelBean comment : serviceList) {
                                    datas.add(comment);
                                    dataSort(false, datas.size() - 1);
                                }
                            }
                        } else {
                            if (isRefresh) {
                                datas.clear();
                                datas = new ArrayList<>();
                                dataSort(true, 0);
                                commentMutiAdapter.setList(data);
//                                commentMutiAdapter.setList(new ArrayList<>());
//                                commentMutiAdapter.setEmptyView(R.layout.empty_comment_layout);
                            }
                        }

                        if (result != null && result.getData() != null && result.getData().getComments().size() > 0) {
                            for (int i = 0; i < result.getData().getComments().size(); i++) {
                                commentIdList.add(result.getData().getComments().get(i).getId());
                                if (result.getData().getComments().get(i).getChildren() != null && result.getData().getComments().get(i).getChildren().size() > 0) {
                                    for (int j = 0; j < result.getData().getComments().get(i).getChildren().size(); j++) {
                                        commentIdList.add(result.getData().getComments().get(i).getChildren().get(j).getId());
                                    }
                                }
                            }
                        }
                        checkComments();
                    }
                });
    }

    /**
     * 对数据重新进行排列
     * 目的是为了让一级评论和二级评论同为item
     * 解决滑动卡顿问题
     *
     * @param position
     */
    private void dataSort(boolean isRefresh, int position) {
        if (datas.isEmpty()) {
            data.add(new MultiItemEntity() {
                @Override
                public int getItemType() {
                    return CommentEntity.TYPE_COMMENT_EMPTY;
                }
            });
            return;
        }

        if (position <= 0) data.clear();
        int posCount = data.size();
        int count = datas.size();
        for (int i = 0; i < count; i++) {
            if (i < position) continue;

            //一级评论
            FirstLevelBean firstLevelBean = datas.get(i);
            if (firstLevelBean == null) continue;
            firstLevelBean.setPosition(i);
            posCount += 2;
            List<SecondLevelBean> secondLevelBeans = firstLevelBean.getChildren();
            if (secondLevelBeans == null || secondLevelBeans.isEmpty()) {
                firstLevelBean.setPositionCount(posCount);
                data.add(firstLevelBean);
                continue;
            }
            int beanSize = secondLevelBeans.size();
            posCount += beanSize;
            firstLevelBean.setPositionCount(posCount);
            data.add(firstLevelBean);

            //二级评论
            for (int j = 0; j < beanSize; j++) {
                SecondLevelBean secondLevelBean = secondLevelBeans.get(j);
                secondLevelBean.setChildPosition(j);
                secondLevelBean.setPosition(i);
                secondLevelBean.setPositionCount(posCount);
                data.add(secondLevelBean);
            }

            //展示更多的item
            if (beanSize <= 20) {
//                CommentMoreBean moreBean = new CommentMoreBean();
//                moreBean.setObjectId(secondLevelBeans.get(secondLevelBeans.size() - 1).getId());
//                moreBean.setParentCommentId(secondLevelBeans.get(secondLevelBeans.size() - 1).getParentUserInfo().getUserId());
//                moreBean.setPosition(i);
//                moreBean.setPositionCount(posCount);
//                moreBean.setTotalCount(firstLevelBean.getTotalCount());
//                data.add(moreBean);
            }
        }

        if (isRefresh) {
            commentMutiAdapter.setList(data);
        } else {
            commentMutiAdapter.setNewInstance(data);
        }
    }

    private void checkComments() {
        if (CommonConfiguration.isLogin(kv)) {
            EasyHttp.post(this)
                    .api(new CheckCommentsLikesApi().setCommentIdList(commentIdList))
                    .request(new HttpCallback<HttpData<CheckCommentsLikesApi.Bean>>(this) {
                        @Override
                        public void onSucceed(HttpData<CheckCommentsLikesApi.Bean> result) {
                            if (result != null && result.getData() != null && result.getData().getLikes().size() > 0) {
                                commentMutiAdapter.setZanState(result.getData().getLikes());
                            }
                        }
                    });
        }
    }

    private void initUpdateImageApi(boolean isWatermark) {
        EasyHttp.post(this).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(headPortraitFile)
                        .setWatermark(isWatermark))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                        flCommentPreviewImage.setVisibility(View.VISIBLE);
                        commentImageBean = result.getData();
                    }
                });
    }

    private void initCommentMakeApi(List<CommentMakeApi.CommentMakeRequest> commentList) {
        EasyHttp.post(this).api(new CommentMakeApi().setType(2).setCommentObjectList(commentList))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        initCommentsLog(true);
                        mCommentId = "";
                        ToastUtils.showShort("回复成功");
                        KeyboardUtils.hideSoftInput(mActivity);
                        etCommentContent.clearFocus();
                        Glide.with(requireActivity()).clear(tvCommentPreviewImage);
                        commentImageBean = null;
                        etCommentContent.setText("");
                        flCommentPreviewImage.setVisibility(View.GONE);
                    }
                });
    }

    @Override
    public void zan(String commentId, boolean isLike) {
        EasyHttp.post(requireActivity())
                .api(new LikeCommentApi().setCommentId(commentId).setLikes(isLike))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
//                        initCommentsLog();
                    }
                });
    }

    @Override
    public void replay(String commentId) {
        this.mCommentId = commentId;
        KeyboardUtils.showSoftInput(mActivity);
        etCommentContent.requestFocus();
    }

    @Override
    public void moreChildren(String parentUserId, String lastId, int position) {
        EasyHttp.post(requireActivity())
                .api(new AppCommentChildrenApi().setType(2).setObjectId(mModelId).setPageSize(CommonConfiguration.page).setParentCommentId(parentUserId).setLastId(lastId))
                .request(new HttpCallback<HttpData<List<SecondLevelBean>>>(this) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(HttpData<List<SecondLevelBean>> result) {
                        if (result != null && result.getData() != null && result.getData().size() > 0) {
                            CommentMoreBean moreBean = (CommentMoreBean) commentMutiAdapter.getData().get(position);
                            List<SecondLevelBean> serviceList = new CopyOnWriteArrayList<>(result.getData());
                            for (SecondLevelBean comment : serviceList) {
                                datas.get((int) moreBean.getPosition()).getChildren().add(comment);
                                dataSort(false, 0);
                            }
                        } else {
//                            //在项目中是从服务器获取数据，其实就是二级评论分页获取
//                            CommentMoreBean moreBean = (CommentMoreBean) commentMutiAdapter.getData().get(position);
//                            SecondLevelBean secondLevelBean = new SecondLevelBean();
//                            secondLevelBean.setContent("");
//                            secondLevelBean.setId("-1");
//                            secondLevelBean.setIsReply(-1);
//                            secondLevelBean.setTotalCount(moreBean.getTotalCount()+1);
//                            secondLevelBean.setMoreComment(false);
//
//                            datas.get((int) moreBean.getPosition()).getChildren().add(secondLevelBean);
//                            dataSort(false, 0);
                        }

                        if (result != null && result.getData() != null && result.getData().size() > 0) {
                            for (int i = 0; i < result.getData().size(); i++) {
                                commentIdList.add(result.getData().get(i).getId());
                            }
                        }
                        checkComments();
                    }
                });
    }
}
